﻿using System.Windows;
using System.Windows.Media;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace Thinktecture.UIAnnotations.Behaviors
{
    public class FocusBehavior : Behavior<Control>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.GotFocus += this.OnGotFocus;
            this.AssociatedObject.LostFocus += this.OnLostFocus;
        }

        private void OnLostFocus(object sender, RoutedEventArgs e)
        {
            ((Control)this.AssociatedObject).Background = new SolidColorBrush(Colors.White);
        }

        private void OnGotFocus(object sender, RoutedEventArgs e)
        {
            ((Control)this.AssociatedObject).Background = this.HighlightBrush;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            if (this.AssociatedObject != null)
            {
                ((Control)this.AssociatedObject).Background = new SolidColorBrush(Colors.White);
                this.AssociatedObject.GotFocus -= this.OnGotFocus;
                this.AssociatedObject.LostFocus -= this.OnLostFocus;
            }
        }

        #region HighlightBrush

        public static readonly DependencyProperty HighlightBrushProperty =
            DependencyProperty.Register("HighlightBrush", typeof(Brush), typeof(FocusBehavior), new PropertyMetadata(new SolidColorBrush(Colors.Yellow)));
        public Brush HighlightBrush { get { return (Brush)GetValue(HighlightBrushProperty); } set { SetValue(HighlightBrushProperty, value); } }

        #endregion
        
    }
}
